<template>
    <view class="bg-white pt-2 alls">
        <!-- 医院信息区域 -->
        <view class="flex flex-col p-2 text-[24rpx] box-border text-gray-800">
            <!-- 延续护理信息标题 -->
            <view class="flex items-center py-1">
                <text class="font-bold whitespace-nowrap text-30rpx">延续护理信息</text>
            </view>

            <!-- 信息延续部分 -->
            <view class="flex items-center gap-2 py-1">
                <text class="font-bold text-gray-600 whitespace-nowrap">信息延续：</text>
                <text class="text-gray-600 whitespace-nowrap">个案记录</text>
                <text class="text-gray-600 whitespace-nowrap">健康档案</text>
            </view>

            <!-- 管理延续部分 -->
            <view class="flex items-center gap-2 py-1">
                <text class="font-bold whitespace-nowrap">管理延续：</text>
                <view class="flex-1 flex gap-2 min-w-0 flex-nowrap overflow-auto" @click="openHospitalSelector">
                    <text class="text-blue-500 underline cursor-pointer whitespace-nowrap">
                        {{ selectedHospital || '广西医科大学第二附属医院' }}
                    </text>
                    <text class="text-blue-500 underline cursor-pointer whitespace-nowrap text-gray-600">
                        {{ selectedTeam || '神经内科' }}
                    </text>
                    <text class="text-blue-500 underline cursor-pointer whitespace-nowrap text-gray-600">
                        {{ selectedDepartment || '一病区' }}
                    </text>
                    <text class="text-blue-500 underline cursor-pointer whitespace-nowrap text-gray-600">
                        {{ selectedProject || '个案记录' }}
                    </text>
                </view>
            </view>

            <!-- 责任人员信息 -->
            <view class="flex items-center gap-2 py-1">
                <text class="font-bold whitespace-nowrap">关系延续：</text>

                <view class="flex-1 flex gap-2 min-w-0 flex-nowrap overflow-auto">
                
                    <view class="flex items-center gap-1">
                        <label class="text-gray-600 whitespace-nowrap">责任医生：</label>
                        <view class="text-blue-500 underline cursor-pointer whitespace-nowrap" @click="openInputPopup('doctor')">
                            {{ doctorName || '张三' }}
                        </view>
                    </view>

                    <view class="flex items-center gap-1">
                        <label class="text-gray-600 whitespace-nowrap">责任护士：</label>
                        <view class="text-blue-500 underline cursor-pointer whitespace-nowrap" @click="openInputPopup('nurse')">
                            {{ nurseName || '张三' }}
                        </view>
                    </view>

                    <view class="flex items-center gap-1">
                        <label class="text-gray-600 whitespace-nowrap">责任护工：</label>
                        <view class="text-blue-500 underline cursor-pointer whitespace-nowrap" @click="openInputPopup('caregiver')">
                            {{ caregiverName || '张三' }}
                        </view>
                    </view>
                </view>
            </view>

            <!-- 订单指导员信息 -->
            <view class="flex items-center gap-2 py-1">
                <text class="font-bold text-gray-600 whitespace-nowrap">订单指导员：</text>
                <view class="flex-1 flex gap-2 min-w-0 flex-nowrap overflow-x-auto">
                    <text class="text-blue-500 underline cursor-pointer whitespace-nowrap flex-shrink-0" @click="openInputPopup('instructor')">
                        {{ instructorName || '张三' }}
                    </text>
                    <text class="text-blue-500 underline cursor-pointer whitespace-nowrap text-gray-600 flex-shrink-0" @click="openInstructorSelector">
                        {{ instructorHospital || '广西医科大学第二附属医院' }}
                    </text>
                    <text class="text-blue-500 underline cursor-pointer whitespace-nowrap text-gray-600 flex-shrink-0" @click="openInstructorSelector">
                        {{ instructorTeam || '神经内科' }}
                    </text>
                    <text class="text-blue-500 underline cursor-pointer whitespace-nowrap text-gray-600 flex-shrink-0" @click="openInstructorSelector">
                        {{ instructorDepartment || '一病区' }}
                    </text>
                    <text class="text-blue-500 underline cursor-pointer whitespace-nowrap text-gray-600 flex-shrink-0" @click="openInstructorSelector">
                        {{ instructorProject || '个案记录' }}
                    </text>
                </view>
            </view>

            <!-- 技术指导机构 -->
            <view class="flex items-center gap-2 py-1">
                <text class="font-bold text-gray-600 whitespace-nowrap">技术指导机构：</text>
                <view class="flex-1 flex gap-2 min-w-0 flex-nowrap overflow-auto" @click="openTechGuideSelector">
                    <text class="text-blue-500 underline cursor-pointer whitespace-nowrap">
                        {{ techGuideHospital || '广西医科大学第二附属医院' }}
                    </text>
                    <text class="text-blue-500 underline cursor-pointer whitespace-nowrap text-gray-600">
                        {{ techGuideTeam || '神经内科' }}
                    </text>
                    <text class="text-blue-500 underline cursor-pointer whitespace-nowrap text-gray-600">
                        {{ techGuideDepartment || '一病区' }}
                    </text>
                    <text class="text-blue-500 underline cursor-pointer whitespace-nowrap text-gray-600">
                        {{ techGuideProject || '个案记录' }}
                    </text>
                </view>
            </view>

            <!-- 服务机构 -->
            <view class="flex items-center gap-2 py-1">
                <text class="font-bold text-gray-600 whitespace-nowrap">服务机构：</text>
                <view class="flex-1 flex gap-2 min-w-0 flex-nowrap overflow-auto" @click="openServiceSelector">
                    <text class="text-blue-500 underline cursor-pointer whitespace-nowrap">
                        {{ serviceHospital || '华声健康医疗（广州）有限公司' }}
                    </text>
                    <text class="text-blue-500 underline cursor-pointer whitespace-nowrap text-gray-600">
                        {{ serviceTeam || '神经内科' }}
                    </text>
                    <text class="text-blue-500 underline cursor-pointer whitespace-nowrap text-gray-600">
                        {{ serviceDepartment || '一病区' }}
                    </text>
                    <text class="text-blue-500 underline cursor-pointer whitespace-nowrap text-gray-600">
                        {{ serviceProject || '个案记录' }}
                    </text>
                </view>
            </view>

            <!-- 健康管家 -->
            <view class="flex items-center gap-2 py-1">
                <text class="font-bold text-gray-600 whitespace-nowrap">健康管家：</text>
                <text class="text-gray-600 whitespace-nowrap">{{ butlerName || '张三' }}</text>
            </view>
        </view>

        <!-- <image class="w-full my-2" :src="pic" mode="widthFix" />
        <view v-html="desc"></view> -->

        <!-- 管理延续医院科室选择器弹窗 -->
        <HospitalDepartmentProjectSelector
            v-model:visible="showHospitalSelector"
            title="选择管理延续信息"
            @confirm="handleHospitalConfirm"
        />

        <!-- 订单指导员医院科室选择器弹窗 -->
        <HospitalDepartmentProjectSelector
            v-model:visible="showInstructorSelector"
            title="选择订单指导员信息"
            @confirm="handleInstructorConfirm"
        />

        <!-- 技术指导机构医院科室选择器弹窗 -->
        <HospitalDepartmentProjectSelector
            v-model:visible="showTechGuideSelector"
            title="选择技术指导机构信息"
            @confirm="handleTechGuideConfirm"
        />

        <!-- 服务机构医院科室选择器弹窗 -->
        <HospitalDepartmentProjectSelector
            v-model:visible="showServiceSelector"
            title="选择服务机构信息"
            @confirm="handleServiceConfirm"
        />

        <!-- 输入弹窗 -->
        <nut-popup v-model:visible="showInputPopup" position="center" round>
            <view class="popup-container">
                <view class="popup-header">
                    <text class="popup-title">{{ popupTitle }}</text>
                </view>
                <view class="popup-content">
                    <nut-input 
                        v-model="inputValue" 
                        :placeholder="`请输入${popupTitle}`" 
                        clearable 
                        class="tag-input" 
                    />
                </view>
                <view class="popup-footer">
                    <nut-button 
                        type="default" 
                        class="flex-1" 
                        @click="handleCancel"
                    >
                        取消
                    </nut-button>
                    <nut-button 
                        type="primary" 
                        class="flex-1" 
                        @click="handleConfirm"
                    >
                        确定
                    </nut-button>
                </view>
            </view>
        </nut-popup>
    </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import HospitalDepartmentProjectSelector from '@/components/HospitalDepartmentProjectSelector.vue'
import { useDemographicInfoStore } from '@/store'
import { request } from '@/service/request'
import { localStg } from '@/utils'
import Taro from '@tarojs/taro'
// import pic from '@/assets/ico/info.jpg';
// const props = defineProps({
//     desc: {
//         type: String,
//         default: ""
//     }
// });
// console.log("description ----", props.desc);

// 获取 demographicStore 实例
const demographicStore = useDemographicInfoStore()

// 获取当前健康管家名字
const butlerName = computed(() => {
    return demographicStore.currentHealthButler?.name || ''
})

// 管理延续数据
const selectedHospital = ref('')
const selectedTeam = ref('')
const selectedDepartment = ref('')
const selectedProject = ref('')

// 订单指导员数据
const instructorName = ref('')
const instructorHospital = ref('')
const instructorTeam = ref('')
const instructorDepartment = ref('')
const instructorProject = ref('')

// 技术指导机构数据
const techGuideHospital = ref('')
const techGuideTeam = ref('')
const techGuideDepartment = ref('')
const techGuideProject = ref('')

// 服务机构数据
const serviceHospital = ref('')
const serviceTeam = ref('')
const serviceDepartment = ref('')
const serviceProject = ref('')

// 信息延续数据（固定值）
const inforExtra = ref('个案记录,健康档案')

// 响应式数据
const doctorName = ref('')
const nurseName = ref('')
const caregiverName = ref('')

// 医院选择器弹窗控制
const showHospitalSelector = ref(false)
const showInstructorSelector = ref(false)
const showTechGuideSelector = ref(false)
const showServiceSelector = ref(false)

// 弹窗控制
const showInputPopup = ref(false)
const inputValue = ref('')
const currentField = ref<'doctor' | 'nurse' | 'caregiver' | 'instructor'>('doctor')
const popupTitle = ref('责任医生')

// 加载状态
const loading = ref(false)

// 打开管理延续医院选择器
function openHospitalSelector() {
    showHospitalSelector.value = true
}

// 处理管理延续医院选择确认
function handleHospitalConfirm(data: {
    hospital: any
    department: any
    team: any
    project: any
}) {
    if (data.hospital) {
        selectedHospital.value = data.hospital.title || ''
    }
    if (data.team) {
        selectedTeam.value = data.team.title || data.team.name || ''
    }
    if (data.department) {
        selectedDepartment.value = data.department.title || data.department.name || ''
    }
    if (data.project) {
        selectedProject.value = data.project.title || data.project.name || ''
    }
    showHospitalSelector.value = false
    // 保存数据
    saveData()
}

// 打开订单指导员选择器
function openInstructorSelector() {
    showInstructorSelector.value = true
}

// 处理订单指导员选择确认
function handleInstructorConfirm(data: {
    hospital: any
    department: any
    team: any
    project: any
}) {
    if (data.hospital) {
        instructorHospital.value = data.hospital.title || ''
    }
    if (data.team) {
        instructorTeam.value = data.team.title || data.team.name || ''
    }
    if (data.department) {
        instructorDepartment.value = data.department.title || data.department.name || ''
    }
    if (data.project) {
        instructorProject.value = data.project.title || data.project.name || ''
    }
    showInstructorSelector.value = false
    // 保存数据
    saveData()
}

// 打开技术指导机构选择器
function openTechGuideSelector() {
    showTechGuideSelector.value = true
}

// 处理技术指导机构选择确认
function handleTechGuideConfirm(data: {
    hospital: any
    department: any
    team: any
    project: any
}) {
    if (data.hospital) {
        techGuideHospital.value = data.hospital.title || ''
    }
    if (data.team) {
        techGuideTeam.value = data.team.title || data.team.name || ''
    }
    if (data.department) {
        techGuideDepartment.value = data.department.title || data.department.name || ''
    }
    if (data.project) {
        techGuideProject.value = data.project.title || data.project.name || ''
    }
    showTechGuideSelector.value = false
    // 保存数据
    saveData()
}

// 打开服务机构选择器
function openServiceSelector() {
    showServiceSelector.value = true
}

// 处理服务机构选择确认
function handleServiceConfirm(data: {
    hospital: any
    department: any
    team: any
    project: any
}) {
    if (data.hospital) {
        serviceHospital.value = data.hospital.title || ''
    }
    if (data.team) {
        serviceTeam.value = data.team.title || data.team.name || ''
    }
    if (data.department) {
        serviceDepartment.value = data.department.title || data.department.name || ''
    }
    if (data.project) {
        serviceProject.value = data.project.title || data.project.name || ''
    }
    showServiceSelector.value = false
    // 保存数据
    saveData()
}

// 打开输入弹窗
function openInputPopup(field: 'doctor' | 'nurse' | 'caregiver' | 'instructor') {
    currentField.value = field
    switch (field) {
        case 'doctor':
            inputValue.value = doctorName.value
            popupTitle.value = '责任医生'
            break
        case 'nurse':
            inputValue.value = nurseName.value
            popupTitle.value = '责任护士'
            break
        case 'caregiver':
            inputValue.value = caregiverName.value
            popupTitle.value = '责任护工'
            break
        case 'instructor':
            inputValue.value = instructorName.value
            popupTitle.value = '订单指导员'
            break
    }
    showInputPopup.value = true
}

// 确认
function handleConfirm() {
    if (inputValue.value.trim()) {
        switch (currentField.value) {
            case 'doctor':
                doctorName.value = inputValue.value.trim()
                break
            case 'nurse':
                nurseName.value = inputValue.value.trim()
                break
            case 'caregiver':
                caregiverName.value = inputValue.value.trim()
                break
            case 'instructor':
                instructorName.value = inputValue.value.trim()
                break
        }
        // 保存数据
        saveData()
    }
    showInputPopup.value = false
}

// 取消
function handleCancel() {
    showInputPopup.value = false
}

/**
 * 解析字符串数据（可能是逗号分隔或JSON格式）
 */
function parseStringData(data: string | undefined): string[] {
    if (!data) return []
    try {
        // 尝试解析为JSON
        const parsed = JSON.parse(data)
        if (Array.isArray(parsed)) return parsed
        return [parsed]
    } catch {
        // 如果不是JSON，按逗号分隔
        return data.split(',').map(s => s.trim()).filter(s => s)
    }
}

/**
 * 加载数据
 */
async function loadData() {
    try {
        loading.value = true
        
        // 获取 idnumber
        const demographicInfo = localStg.get('demographicInfo')
        const idnumber = demographicInfo?.idNumber || demographicInfo?.idnumber || ''
        
        if (!idnumber) {
            console.warn('未找到身份证号码，无法加载数据')
            return
        }

        // 调用接口获取最新记录
        const { error, success } = await request.get<any>(
            '/extra_nurse_info/extraNurseInfo/list',
            {
                idnumber: idnumber,
                pageNo: 1,
                pageSize: 1,
                column: 'createTime',
                order: 'desc'
            },
            { useErrMsg: true }
        )

        console.log("success ------ 身份证查找", success)

        if (error || !success?.records || success.records.length === 0) {
            console.log('未找到延续护理信息记录')
            return
        }

        const record = success.records[0]
        console.log('加载延续护理信息:', record)

        // 解析并赋值数据
        if (record.inforExtra) {
            inforExtra.value = record.inforExtra
        }

        // 解析管理延续（格式：医院,科室,病区,项目）
        if (record.manaExtra) {
            const manaParts = parseStringData(record.manaExtra)
            if (manaParts.length >= 1) selectedHospital.value = manaParts[0]
            if (manaParts.length >= 2) selectedTeam.value = manaParts[1]
            if (manaParts.length >= 3) selectedDepartment.value = manaParts[2]
            if (manaParts.length >= 4) selectedProject.value = manaParts[3]
        }

        // 责任人员
        if (record.primaryDoc) doctorName.value = record.primaryDoc
        if (record.primaryNurse) nurseName.value = record.primaryNurse
        if (record.primaryCare) caregiverName.value = record.primaryCare

        // 解析订单指导员（格式：指导员姓名,医院,科室,病区,项目）
        if (record.orderGuide) {
            const orderParts = parseStringData(record.orderGuide)
            if (orderParts.length >= 1) {
                // 第一个是指导员姓名，独立存储，不关联医生信息
                instructorName.value = orderParts[0]
            }
            if (orderParts.length >= 2) instructorHospital.value = orderParts[1]
            if (orderParts.length >= 3) instructorTeam.value = orderParts[2]
            if (orderParts.length >= 4) instructorDepartment.value = orderParts[3]
            if (orderParts.length >= 5) instructorProject.value = orderParts[4]
        }

        // 解析技术指导机构（格式：医院,科室,病区,项目）
        if (record.techOrg) {
            const techParts = parseStringData(record.techOrg)
            if (techParts.length >= 1) techGuideHospital.value = techParts[0]
            if (techParts.length >= 2) techGuideTeam.value = techParts[1]
            if (techParts.length >= 3) techGuideDepartment.value = techParts[2]
            if (techParts.length >= 4) techGuideProject.value = techParts[3]
        }

        // 解析服务机构（格式：医院,科室,病区,项目）
        if (record.serviceOrg) {
            const serviceParts = parseStringData(record.serviceOrg)
            if (serviceParts.length >= 1) serviceHospital.value = serviceParts[0]
            if (serviceParts.length >= 2) serviceTeam.value = serviceParts[1]
            if (serviceParts.length >= 3) serviceDepartment.value = serviceParts[2]
            if (serviceParts.length >= 4) serviceProject.value = serviceParts[3]
        }

    } catch (err) {
        console.error('加载延续护理信息失败:', err)
        Taro.showToast({ title: '加载数据失败', icon: 'error' })
    } finally {
        loading.value = false
    }
}

/**
 * 保存数据
 */
async function saveData() {
    try {
        loading.value = true

        // 获取 idnumber
        const demographicInfo = localStg.get('demographicInfo')
        const idnumber = demographicInfo?.idNumber || demographicInfo?.idnumber || ''
        
        if (!idnumber) {
            Taro.showToast({ title: '未找到身份证号码', icon: 'error' })
            return
        }

        // 组合管理延续数据
        const manaExtra = [
            selectedHospital.value || '广西医科大学第二附属医院',
            selectedTeam.value || '神经内科',
            selectedDepartment.value || '一病区',
            selectedProject.value || '个案记录'
        ].join(',')

        // 组合订单指导员数据
        const orderGuide = [
            instructorName.value || '张三',
            instructorHospital.value || '广西医科大学第二附属医院',
            instructorTeam.value || '神经内科',
            instructorDepartment.value || '一病区',
            instructorProject.value || '个案记录'
        ].join(',')

        // 组合技术指导机构数据
        const techOrg = [
            techGuideHospital.value || '广西医科大学第二附属医院',
            techGuideTeam.value || '神经内科',
            techGuideDepartment.value || '一病区',
            techGuideProject.value || '个案记录'
        ].join(',')

        // 组合服务机构数据
        const serviceOrg = [
            serviceHospital.value || '华声健康医疗（广州）有限公司',
            serviceTeam.value || '神经内科',
            serviceDepartment.value || '一病区',
            serviceProject.value || '个案记录'
        ].join(',')

        // 构建完整数据
        const data = {
            idnumber: idnumber,
            inforExtra: inforExtra.value,
            manaExtra: manaExtra,
            primaryDoc: doctorName.value || '',
            primaryNurse: nurseName.value || '',
            primaryCare: caregiverName.value || '',
            orderGuide: orderGuide,
            techOrg: techOrg,
            serviceOrg: serviceOrg,
            heathMag: butlerName.value || ''
        }

        console.log('保存延续护理信息:', data)

        // 调用保存接口
        const { error } = await request.post<any>(
            '/extra_nurse_info/extraNurseInfo/add',
            data,
            { useErrMsg: true }
        )

        if (error) {
            console.error('保存失败:', error)
            Taro.showToast({ title: error.message || '保存失败', icon: 'error' })
        } else {
            console.log('保存成功')
            // 不显示成功提示，避免频繁弹窗
        }

    } catch (err) {
        console.error('保存延续护理信息失败:', err)
        Taro.showToast({ title: '保存失败', icon: 'error' })
    } finally {
        loading.value = false
    }
}

// 组件挂载时加载数据
onMounted(() => {
    loadData()
})
</script>

<style lang="scss" scoped>
.alls{
    color: #333;
    font-size: 20rpx;
    padding: 10rpx;
    img{
        width: 100% !important;
    }
    view{
        width: 100% !important;
    }
}

.popup-container {
    width: 90% !important;
    max-width: 600rpx !important;
    padding: 40rpx;
    background: white;
    border-radius: 20rpx;
    box-sizing: border-box;
}

.popup-header {
    text-align: center;
    margin-bottom: 30rpx;
    box-sizing: border-box;
}

.popup-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    word-wrap: break-word;
    box-sizing: border-box;
}

.popup-content {
    margin-bottom: 30rpx;
    box-sizing: border-box;
}

.tag-input {
    width: 100%;
    box-sizing: border-box;
    
    :deep(.nut-input__inner) {
        box-sizing: border-box;
    }
}

.popup-footer {
    display: flex;
    gap: 12rpx;
    align-items: center;
    box-sizing: border-box;
    
    :deep(.nut-button) {
        flex: 1;
        min-width: 0;
        box-sizing: border-box;
    }
}

.text-blue-500 {
    color: #3b82f6;
}

.underline {
    text-decoration: underline;
}

.cursor-pointer {
    cursor: pointer;
}

/* 滚动容器优化 */
.overflow-x-auto {
    overflow-x: auto;
    overflow-y: hidden;
    -webkit-overflow-scrolling: touch;
    scrollbar-width: none; /* Firefox */
    -ms-overflow-style: none; /* IE 10+ */
}

.overflow-x-auto::-webkit-scrollbar {
    display: none; /* Chrome Safari */
}

.flex-shrink-0 {
    flex-shrink: 0;
}
</style>